import { Component, ElementRef, HostListener, OnInit, ViewChild } from '@angular/core';
import { NzInputDirective, NzMessageService, NzModalService } from 'ng-zorro-antd';
import { FetchService } from '../../../../core/net/fetch.service';
import { DataReportService } from '../../data-report.service';
import { HttpClient } from '@angular/common/http';
import * as moment from 'moment';
import * as _ from 'lodash';
const irrHash = {
    val1: '农业用水',
    val2: '工业用水',
    val3: '生活用水',
    val4: '生态用水'
};
@Component({
  selector: 'app-mng-water-usage',
  templateUrl: './mng-water-usage.component.html',
  styleUrls: ['./mng-water-usage.component.scss', '../mng-water-report.component.scss']
})
export class MngWaterUsageComponent implements OnInit {
    listData = [];
    roleName = JSON.parse(localStorage.roleInfo).name;

    contentTitle: string;
    today: Date = new Date();
    datePicker: Date = new Date();
    range: Date[];
    quickTimeSelect = null;
    tableData = [];
    totalTableData = [];
    summerHead = [];
    baseOpt: any = {
        title: {
            left: 'center',
            textStyle: {
                color: '#777',
                fontSize: 16
            }
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            data: [],
            bottom: 0
        },
        xAxis: {
            type: 'category',
            axisTick: {
                alignWithLabel: true
            },
            data: []
        },
        yAxis: {
            type: 'value'
        },
        series: []
    };
    irrOptChange: any = {};
    irrHistoryData = [];
    frId: string;
    resDataCache: any;
    srId: string;

    modalFirstHead = [];

    modalTitle: string = '用水量历史数据';
    modalShow: boolean = false;
    nzBodyStyle: any = {
        padding: '16px 20px 0'
    };
    submitModalStyle: any = {
        maxHeight: '730px',
        overflow: 'auto'
    };
    submitModalTitle: string = '当日值填报';
    submitModalShow: boolean = false;
    submitContentTitle: string = '填报';
    submitTableHead = [];
    editId: string | null;
    editCache: { [key: string]: { edit: boolean; data: any } } = {};

    @ViewChild(NzInputDirective, {read: ElementRef}) inputElement: ElementRef;

    @HostListener('window:click', ['$event'])
    handleClick(e: MouseEvent): void {
        if (this.inputElement && e.target['tagName'] !== 'INPUT') {
            Object.keys(this.editCache).forEach(key => {
                this.editCache[key].edit = false;
            });
        }
    }

    constructor(private fetchService: FetchService,
                private dataReportService: DataReportService,
                private http: HttpClient,
                private message: NzMessageService,
                private modal: NzModalService) {
    }

    ngOnInit() {
        this.fetchService.post<any>('muw/wrsMuwFr/list', {type: '2'}).subscribe(res => {
            this.frId = res[0].id;
            this.getDetailData(this.today);
        });
    }

    updateEditCache(): void {
        this.tableData.forEach(item => {
            this.editCache[item.srId] = {
                edit: true,
                data: {...item}
            };
        });
    }

    startEdit(srId: string, event: MouseEvent): void {
        event.preventDefault();
        event.stopPropagation();
        this.editCache[srId].edit = true;
        this.editId = srId;
    }

    getDetailData(date): void {
        const params = {
            frId: this.frId,
            type: 3,
            date: moment(date).valueOf()
        };
        this.fetchService.post<any>('muw/wrsMuwIrrData/list', params).subscribe(res => {
            this.summerHead = res.datas[0].irrDatas.map(o => {
                return {
                    name: o.trIrrName,
                    dailyName: `${o.trIrrName}_daily`,
                    accName: `${o.trIrrName}_acc`
                };
            });
            // this.resDataCache = _.cloneDeep(res);
            res.datas.forEach(item => {
                this.summerHead.forEach(props => {
                    const obj = _.find(item.irrDatas, food => {
                        return food.trIrrName === props.name;
                    });
                    item[props.dailyName] = obj.val;
                    item[props.accName] = obj.valTotal;
                });
            });
            // this.tableData = res.datas;
            this.totalTableData = res.datas;
            if (this.totalTableData.length) {
                this.getChartData(this.totalTableData[0]);
            }
            // this.updateEditCache();
        });
    }
    getChartData(row): void {
        this.fetchService.post<any>('muw/wrsMuwIrrData/historySrList', {
            type: '3',
            stDate: moment().subtract(30, 'days').format('YYYY-MM-DD'),
            edDate: moment().format('YYYY-MM-DD'),
            srId: row.srId
        }).subscribe(res => {
            if (Array.isArray(res)) {
                this.irrOptChange = {
                    title: {
                        text: `${row.srName}用水量`,
                    },
                    legend: {
                        data: Object.values(irrHash)
                    },
                    xAxis: {
                        data: res.map(item => {
                            return item.time;
                        })
                    },
                    yAxis: {
                        name: '用水量(万m³)'
                    },
                    series: Object.keys(irrHash).map(key => {
                        return {
                            name: irrHash[key],
                            type: "bar",
                            barWidth: '10%',
                            data: res.map(item => {
                                return item[key];
                            })
                        };
                    })
                };
            }
        });
    }
    openSubmitModal(): void {
        this.submitModalShow = true;
        this.submitContentTitle = `${moment(this.today).format('YYYY年M月D日')}数据填报`;
        this.getSubmitModalData();
    }

    /**
     * 获取填报页面报表数据
     */
    getSubmitModalData(): void {
        const params = {
            frId: this.frId,
            type: 3,
            hj: 'false',  // 无合计列
            date: moment(this.today).valueOf()
        };
        this.fetchService.post<any>('muw/wrsMuwIrrData/list', params).subscribe(res => {
            this.resDataCache = _.cloneDeep(res);
            this.submitTableHead = res.datas[0].irrDatas.map(o => {
                return {
                    name: o.trIrrName,
                    dailyName: `${o.trIrrName}_daily`,
                    accName: `${o.trIrrName}_acc`
                };
            });
            // this.resDataCache = _.cloneDeep(res);
            res.datas.forEach(item => {
                this.submitTableHead.forEach(props => {
                    const obj = _.find(item.irrDatas, food => {
                        return food.trIrrName === props.name;
                    });
                    item[props.dailyName] = obj.hisVal;
                });
            });
            this.tableData = res.datas;
            this.updateEditCache();
        });
    }
    submit(): void {
        this.modal.confirm({
            nzTitle: '确认提交并上报？',
            nzContent: '',
            nzOnOk: () => {
                const params = _.assign(this.resDataCache, {statu: 2, datas: this.getNewTableData()});
                this.fetchService.post<any>('muw/wrsMuwIrrData/add', params).subscribe(res => {
                    this.message.success('提交成功');
                    this.getSubmitModalData();
                });
            }
        });
    }

    save(): void {
        const params = _.assign(this.resDataCache, {statu: 1, datas: this.getNewTableData()});
        this.fetchService.post<any>('muw/wrsMuwIrrData/add', params).subscribe(res => {
            this.message.success('暂存成功');
            this.getSubmitModalData();
        });
    }

    private getNewTableData(): Array<any> {
        const table = _.cloneDeep(this.tableData);
        table.forEach(item => {
            this.submitTableHead.forEach(props => {
                item.irrDatas.forEach(food => {
                    if (food.trIrrName === props.name) {
                        food.val = item[props.dailyName];
                    }
                });
            });
        });
        return table.map(item => {
            return _.pick(item, ['srId', 'srName', 'irrDatas']);
        });
    }

    openDetailModal(): void {
        this.modalShow = true;
        this.quickTimeSelect = '7';
        this.quickSelect();
    }

    export(): void {
        const param = {
            frId: this.frId ? this.frId : '',
            type: 3
        };
        this.fetchService.export('muw/wrsMuwIrrData/export', param).subscribe((res: any) => {
            const blob = new Blob([res], {type: 'application/vnd.ms-excel    application/x-excel;charset=utf-8'});
            const elink = document.createElement('a');

            elink.download = `用水量.xlsx`;
            elink.href = URL.createObjectURL(blob);
            document.body.appendChild(elink);
            elink.click();
            URL.revokeObjectURL(elink.href); // 释放URL 对象
            document.body.removeChild(elink);
        });
    }

    print(): void {
    }

    onCancel() {
        this.modalShow = false;
    }

    onSubmitCancel() {
        this.submitModalShow = false;
        this.getDetailData(this.today);
    }

    onRangeChange(result: Date[] | number[]): void {
        const start = result[0] ? moment(result[0]).valueOf() : moment().valueOf();
        const end = result[1] ? moment(result[1]).valueOf() : moment().valueOf();
        const params = {
            frId: this.frId,
            type: 3,
            startDate: start,
            endDate: end
        };
        this.fetchService.post<any>('muw/wrsMuwIrrData/historyDataList', params).subscribe(res => {
            res.forEach(data => {
                data.date = moment(data.time).format('YYYY-MM-DD');
            });
            this.irrHistoryData = _.reverse(res);
            if (this.irrHistoryData.length > 0) {
                this.modalFirstHead = this.irrHistoryData[0].datas.map(o => {
                    return o.srName;
                });
            }
        });
    }

    quickSelect(): void {
        const start = moment().subtract(parseInt(this.quickTimeSelect, 10), 'days').valueOf();
        const end = moment().valueOf();
        this.onRangeChange([start, end]);
    }

    warning() {
        this.message.warning("正在开发中");
    }
}
